import java.util.Comparator;
import java.util.PriorityQueue;

class Student implements Comparable<Student> {
    public int age;

    public Student(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        //return this.age -o.age;
        return o.age - this.age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                '}';
    }
}

class  ImpMaxComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        //return o1.compareTo(o2);
        return o2.compareTo(o1);
    }
}

class  ImpMinComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
}

public class Test {

    public int[] smallestK(int[] array, int k) {
        if(array == null || k <= 0) {
            return null;
        }
        ImpMaxComparator impMaxComparator = new ImpMaxComparator();
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(impMaxComparator);

        //1.把前K个元素 创建成大根堆
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(array[i]);
        }

        //遍历剩下的 N-K 个元素
        for (int i = k; i < array.length; i++) {
            int peekVal = priorityQueue.peek();
            if(peekVal > array[i]) {
                priorityQueue.poll();
                priorityQueue.offer(array[i]);
            }
        }
        int[] ret = new int[k];
        for (int i = 0; i < k; i++) {
            ret[i] = priorityQueue.poll();
        }
        return ret;
    }
}
